<template>
  <button class="nb-button" @click="changeNum(-1)">-</button>
  <input type="text" class="nb-input" :value="num" @change="blurHandler" />
  <button class="nb-button" @click="changeNum(1)">+</button>
</template>

<script setup>
import { ref, watch } from 'vue'

const { initialValue } = defineProps({
  initialValue: {
    type: Number,
    default: 1
  }
})

const emit = defineEmits(['change'])

const num = ref(initialValue)
const changeNum = (step) => {
  if (num.value + step <= 0) {
    return
  }
  num.value += step
}

const blurHandler = (e) => {
  // console.log(e.currentTarget.value)
  num.value = e.currentTarget.value
}

watch(num, (newValue, oldValue) => {
  console.log('xxx', newValue, oldValue)
  newValue = parseInt(newValue)
  // emit('change', newValue)

  if (newValue <= 0 || isNaN(newValue)) {
    // 非法的边界情况
    num.value = parseInt(oldValue)
  } else {
    // 正确的情况
    emit('change', newValue)
  }
})
</script>

<style scoped>
.nb-input {
  width: 40px;
  text-align: center;
  margin: 0 1px;
}
</style>
